interface DragDividerConfigs {
    /**
     * 左侧flex值，取值：0~1,默认为：0.5，右侧默认为：1减去左侧值
     */
    leftFlex?: number
    /**
     * 最小值，默认为：0.2
     */
    min?: number
    /**
     * 最大值，默认为：0.8
     */
    max?: number
}

export const useDragDivider = (parentTarget?: Ref<HTMLElement | undefined, HTMLElement | undefined>, configs?: DragDividerConfigs) => {
    let isDragging = false
    let defaultLeftFlex = 0.5
    const min = configs?.min ?? 0.2
    const max = configs?.max ?? 0.8

    const leftFlex = ref(configs?.leftFlex ?? defaultLeftFlex)
    const rightFlex = ref(configs?.leftFlex ?? defaultLeftFlex)

    const onMousedown = (event: MouseEvent) => {
        if (!parentTarget?.value) return
        isDragging = true
        rightFlex.value = (window.innerWidth - event.clientX) / parentTarget?.value.offsetWidth
        leftFlex.value = 1 - rightFlex.value
        document.body.style.userSelect = 'none'
        document.body.style.cursor = 'col-resize'
    }
    const handleMouseMove = (event: MouseEvent) => {
        if (!parentTarget?.value) return
        if (!isDragging) return
        rightFlex.value = (window.innerWidth - event.clientX) / parentTarget?.value.offsetWidth
        if (rightFlex.value < min) {
            rightFlex.value = min
        } else if (rightFlex.value > max) {
            rightFlex.value = max
        }
        leftFlex.value = 1 - rightFlex.value
    }

    const handleMouseUp = () => {
        isDragging = false
        document.body.style.userSelect = ''
        document.body.style.cursor = 'default'
    }

    onMounted(() => {
        document.addEventListener('mousemove', handleMouseMove)
        document.addEventListener('mouseup', handleMouseUp)
    })

    onUnmounted(() => {
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
    })

    return { leftFlex, rightFlex, onMousedown }
}
